import CredentialsProvider from "next-auth/providers/credentials"

import { getUserByOpenid, createUser } from "./lib/userService"

export const authOptions = {
  providers: [
    {
      id: "wechat",
      name: "WeChat",
      type: "oauth",
      wellKnown: "",
      authorization: {
        url: "https://open.weixin.qq.com/connect/oauth2/authorize",
        params: {
          appid: process.env.WECHAT_APP_ID,
          redirect_uri: `${process.env.NEXTAUTH_URL}/ty/api/auth/callback/wechat`,
          response_type: "code",
          scope: "snsapi_userinfo",
        }
      },
      token: {
        url: "https://api.weixin.qq.com/sns/oauth2/access_token",
        async request({ client, params, checks, provider }) {
          console.log("Token request params:", params);

          // 构建完整的请求参数
          const requestParams = {
            appid: process.env.WECHAT_APP_ID,
            secret: process.env.WECHAT_APP_SECRET,
            code: params.code,
            grant_type: 'authorization_code'
          };

          const response = await fetch(
            `${provider.token.url}?` + new URLSearchParams(requestParams)
          );

          const tokens = await response.json();

          if (tokens.errcode) {
            console.error("WeChat OAuth Error:", tokens);
            throw new Error(`WeChat OAuth Error: ${tokens.errmsg}`);
          }

          return {
            tokens: {
              access_token: tokens.access_token,
              refresh_token: tokens.refresh_token,
              openid: tokens.openid,
            }
          };
        }
      },
      userinfo: {
        url: "https://api.weixin.qq.com/sns/userinfo",
        async request({ tokens, provider }) {
          const response = await fetch(
            `${provider.userinfo.url}?access_token=${tokens.access_token}&openid=${tokens.openid}&lang=zh_CN`
          );
          const profile = await response.json();

          if (profile.errcode) {
            throw new Error(`WeChat Userinfo Error: ${profile.errmsg}`);
          }

          return profile;
        }
      },
      profile(profile) {
        return {
          id: profile.openid,
          name: profile.nickname || '半岛新星',
          image: profile.headimgurl,
        }
      },
      clientId: process.env.WECHAT_APP_ID,
      clientSecret: process.env.WECHAT_APP_SECRET,
    },
    CredentialsProvider.default({
      id: 'credentials',
      name: 'Test Account',
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (process.env.NEXT_PUBLIC_ENABLE_TEST_AUTH === 'true' &&
            credentials?.username === 'test' &&
            credentials?.password === 'test') {
          // 测试教练
          // const user = {
          //   name: '测试教练',
          //   gender: 'male',
          //   phone_number: '13800138000',
          //   role: 'coach',
          //   openid: 'test-coach-001',
          //   branch_campus_id: '8a7b7d4c-f2bb-4e40-966c-916754cfdc94',
          //   status: 'active',
          //   memo: 'test coach',
          // };
          // 测试客户
          // const user = {
          //   name: '测试客户',
          //   gender: 'female',
          //   phone_number: '13800138000',
          //   role: 'client',
          //   openid: 'test-client-001',
          // };
          // 测试管理员
          const user = {
            name: 'hz测试管理员',
            role: 'admin',
            openid: 'test-admin-0003',
            gender: 'male',
            phone_number: '13800138000',
          };
          return user;
        }
        console.log('Authorization failed');
        return null;
      }
    })
  ],
  pages: {
    signIn: 'ty/zh/login',
    error: 'ty/zh/login',
  },
  //signIn 回调 -> jwt 回调 -> session 回调
  callbacks: {
    // 2. 然后执行：创建 JWT token
    async jwt({ token, user, account }) {
      // 首次登录时，user 和 account 都会有值, 后续刷新时，只有 token 有值
      console.log('2.jwt 回调', {token, user, account})
      if (user) {
        token.id = user.id;
        token.openid = user.openid;
        token.role = user.role;
        token.name = user.name || '半岛新星';
        token.phone_number = user.phone_number;
        const userInfo = await getUserByOpenid(token.openid);
        if (userInfo) {
          token.id = userInfo.id;
          token.phone_number = userInfo.phone_number;
        }
      }

      if (account && account.provider === "wechat") {
        token.accessToken = account.access_token;
        token.refreshToken = account.refresh_token;
        token.openid = account.openid;
      }
      return token;
    },
      // 3. 最后执行：创建客户端 session
    async session({ session, token }) {
      console.log('3.session 回调', {session, token})
      if (token) {
        session.user.id = token.id;
        session.user.role = token.role;
        session.user.openid = token.openid;
        session.user.image = token.picture;
        session.user.phone_number = token.phone_number;
        session.user.name = token.name || '半岛新星';
      }
      return session;
    },
    // 1. 首先执行：处理初始登录，可以在这里创建/更新用户
    async signIn({ user, account, profile }) {
      console.log('1.signIn 回调', {user, account, profile} )
      if (account.provider === "wechat") {
        try {
          let userInfo = await getUserByOpenid(profile.openid);
          if (!userInfo) {
            userInfo = await createUser({
              wx_openid: profile.openid,
              name: profile.nickname || '半岛新星',
              role: "client",
              status: "inactive",
              memo: "sign from wechat",
              gender: profile.sex === 0 ? 'male' : 'female',
            });
          }

          // 更新 user 对象，使用数据库生成的 id
          user.id = userInfo.id;
          return true;
        } catch (error) {
          console.error("SignIn Error:", error);
          return false;
        }
      }

      if (account.provider === "credentials") {
        const existingUser = await getUserByOpenid(user.openid);
        if (!existingUser) {
          await createUser({
            name: user.name,
            role: user.role,
            wx_openid: user.openid,
            gender: user.gender,
            phone_number: user.phone_number,
            status: 'active',
            memo: 'sign from credentials mock',
          });
        }
        return true;
      }

      return false;
    },
  },
  session: {
    strategy: "jwt"
  }
}
